package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.Teacher;
import com.example.demo.entity.User;
import com.example.demo.mapper.TeacherMapper;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 专门用来映射我们的ajax
 */
@RestController
public class ajaxController {
    @Autowired
    TeacherMapper teacherMapper;

    @Autowired
    UserMapper userMapper;

    //只有当我们的前端数据发送过来为JSon格式的时候  才可以使用 RequestBody注解
    @PostMapping("/editTeacher")
    public int editTeacherEnter(@RequestBody Teacher teacher){
        return   teacherMapper.updateById(teacher);

    }


    @RequestMapping("/selectTeacherByUsername")
    public List<Teacher>  selectTeacherByUsername(@RequestParam("username") String username){
        //xian new  一个条件构造器
        QueryWrapper<Teacher> qw = new QueryWrapper<Teacher>();
        qw.eq("username",username);
        return teacherMapper.selectList(qw);
    }


    @PostMapping("/updateTeacher")
    public int updateTeacher(@RequestParam("id") int id,
                             @RequestParam("field") String field,
                             @RequestParam("value") String value){
    return  teacherMapper.updateTeacherById(id, field, value);

    }

    @GetMapping("/userLogin")
    public int userLogin(@RequestParam("username") String username,
                         @RequestParam("password") String password,
                         HttpSession session){
        //条件构造器
        QueryWrapper<User> qw = new QueryWrapper<User>();
        qw.eq("username",username);
        User user1 = userMapper.selectOne(qw);
        if(user1 == null){
            //账户名不存在
            return 0;
        }else if(user1.getPassword().equals(password)){
            //登录成功
            session.setAttribute("user",user1);
            return 1;
        }else{
            //密码错误
            return 2;
        }

//        QueryWrapper<User> qw = new QueryWrapper<User>();
//                qw.eq("username",username).eq("password",password);
//                User user = userMapper.selectOne(qw);
    }
}
